﻿Imports System.IO
Public Class Form1
    Dim proc As New Process 'make it global so dat we can kill it from outside
    Function startConverstion()
        'destination path
        Dim BasePath As String = "H:\My Crap\!~Sandbox\TV\Converting"

        Application.DoEvents()
        cycledir(BasePath)
        Return 0
    End Function

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub cycledir(ByVal dir As String) 'bring in directory to parse

        Dim i As Integer
        Dim Directories() As String = Directory.GetDirectories(dir) 'put all directories into an array

        'loop through each one check for additional directories with in
        If Directories.Count <> 0 Then
            For i = 0 To UBound(Directories)
                Application.DoEvents()
                cycledir(Directories(i)) 'if a directory exists inside the directory passed in, parse that one.
            Next
        End If

        cyclefile(dir) 'cycle through the files.
        Application.DoEvents()

    End Sub

    Private Sub cyclefile(ByVal dir As String)
        'dir is conversition and save path
        Control.CheckForIllegalCrossThreadCalls = False
        Dim fi As FileInfo
        Dim filename As String
        Dim exepath As String = Application.StartupPath + "\bin\ffmpeg.exe"

        Dim startinfo As New System.Diagnostics.ProcessStartInfo
        Dim sr As StreamReader

        'get all files in the passed dir
        Dim Files() As String = Directory.GetFiles(dir)
        'start cycling through the files.
        For i = 0 To Files.Count - 1
            Application.DoEvents()

            fi = New FileInfo(Files(i)) 'get file info of the file to convert
            If fi.Name.EndsWith(".mp4") OrElse fi.Name.EndsWith(".mkv") Then
                Me.lblInfo.Text = Files.Count - (i + 1) & " Files Left"
                filename = fi.Name.Remove(fi.Name.Length - 4, 4) 'get rid of extension
                filename = filename & ".avi" 'ending result filename to convert to 
                'Dim cmd As String = " -threads 2  -y -i """ + dir + "\" + fi.Name + """ -f avi -r 29.97 -vcodec libxvid -vtag XVID -s 704x384 -aspect 16:9 -maxrate 1800k -b 1500k -qmin 3 -qmax 5 -bufsize 4096 -mbd 2 -bf 2 -acodec libmp3lame -ar 48000 -ab 128k -ac 2 """ + dir + "\" + filename + """" 'ffmpeg commands -y replace"
                Dim cmd As String = " -threads 2  -y -i """ + dir + "\" + fi.Name + """ -f avi -r 29.97 -vcodec libxvid -vtag XVID -s 640x360 -aspect 16:9 -maxrate 1800k -b 1500k -qmin 3 -qmax 5 -bufsize 4096 -mbd 2 -bf 2 -acodec libmp3lame -ar 48000 -ab 128k -ac 2 """ + dir + "\" + filename + """" 'ffmpeg commands -y replace"
                Dim ffmpegOutput As String
                Me.txtFile.Text = "Converting " + filename

                ' all parameters required to run the process
                startinfo.FileName = exepath
                startinfo.Arguments = cmd
                startinfo.UseShellExecute = False
                startinfo.WindowStyle = ProcessWindowStyle.Hidden
                startinfo.RedirectStandardError = True
                startinfo.RedirectStandardOutput = True
                startinfo.CreateNoWindow = True
                proc.StartInfo = startinfo
                proc.Start() ' start the process
                'Me.lblInfo.Text = "Conversion in progress... Please wait..."
                sr = proc.StandardError 'standard error is used by ffmpeg
                Me.btnStart.Enabled = False
                Do
                    If BackgroundWorker1.CancellationPending Then 'check if a cancellation request was made
                        'delete current processing file.
                        
                        proc.Kill()
                        Exit Sub
                    End If
                    ffmpegOutput = sr.ReadLine
                    Me.txtProgress.Text = ffmpegOutput
                Loop Until proc.HasExited And ffmpegOutput = Nothing Or ffmpegOutput = ""

                Me.txtProgress.Text = ""
                File.Move(dir & "\" & filename, "H:\My Crap\!~Sandbox\TV\Review\" & filename)
                File.Delete(dir + "\" + fi.Name)
            End If
        Next
        Me.lblInfo.Text = "Completed"

    End Sub

    Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
        Try

            BackgroundWorker1.CancelAsync()
            If btnStart.Enabled = False Then
                lblInfo.Text = ("Conversion Canceled!")
                MsgBox("Conversion has been cancelled!", MsgBoxStyle.Exclamation)
                btnStart.Enabled = True
            Else
                MsgBox("Start conversion first", MsgBoxStyle.Critical)
            End If

            proc.Kill()

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        startConverstion()
    End Sub


End Class
